#include <stdio.h>
#include <errno.h>
#include <string.h>

#include "struct.h"
#include "cJSON.h"



int read_json_file(char *filename,mosquitto_t *mqtt)
{
	FILE		*fp;
	long		file_size;
	int        rv=-1;
	mosquitto_t			mqtt_t;

	fp=fopen(filename,"r");
	if(fp==NULL)
	{
		printf("Error opening file:%s\n",strerror(errno));
		return -1;
	}

	fseek(fp,0,SEEK_END);
	file_size=ftell(fp);

	fseek(fp,0,SEEK_SET);
	//	printf("file_size:%ld\n",file_size);

	char json_string[file_size+1];

	fread(json_string,1,file_size,fp);

	//printf("Json config file:\n%s\n",json_string);
	fclose(fp);

	cJSON *json = cJSON_Parse(json_string);

	if(json==NULL)
	{

		printf("Error before:[%s]\n",cJSON_GetErrorPtr());
		return -1;
	}
	else
	{
#if 0
		printf("Start parse:\n");

		printf("clientId:%s\n",cJSON_GetObjectItem(json,"clientId")->valuestring);
		printf("username:%s\n",cJSON_GetObjectItem(json,"username")->valuestring);
		printf("hostname:%s\n",cJSON_GetObjectItem(json,"hostname")->valuestring);
		printf("passwd:%s\n",cJSON_GetObjectItem(json,"passwd")->valuestring);
		printf("port:%d\n",cJSON_GetObjectItem(json,"port")->valueint);
		printf("topic:%s\n",cJSON_GetObjectItem(json,"topic")->valuestring);
		printf("\n---1----\n");

#endif

		strcpy(mqtt->clientId,cJSON_GetObjectItem(json,"clientId")->valuestring);
		strcpy(mqtt->username,cJSON_GetObjectItem(json,"username")->valuestring);
		strcpy(mqtt->hostname,cJSON_GetObjectItem(json,"hostname")->valuestring);   
		strcpy(mqtt->passwd,cJSON_GetObjectItem(json,"passwd")->valuestring);
		//strcpy(mqtt->port,cJSON_GetObjectItem(json,"port")->valueint);
		mqtt->port = cJSON_GetObjectItem(json,"port")->valueint;
		strcpy(mqtt->topic,cJSON_GetObjectItem(json,"topic")->valuestring);
#if 0
		printf(\n)
		printf("read_json_file")
		printf(\n)
		printf("clientId:%s\n",mqtt->clientId);
        printf("username:%s\n",mqtt->username);
        printf("hostname:%s\n",mqtt->hostname);
        printf("passwd:%s\n",mqtt->passwd);
        printf("port:%d\n",mqtt->port);
        printf("topic:%s\n",mqtt->topic);
#endif

	}

	cJSON_Delete(json);


}


#if 0
int read_json_file(char *filename);


int main(int argc,char **argv)
{
	int 		rv=-1;
	if(argc<2)
	{
		printf("Usage: %s filename.json\n",argv[0]);

		return -1;
	}

	rv=read_json_file(argv[1]);
	if(rv<0)
	{
		printf("Read json file failure!");
		return -1;
	}


}
#endif






